package com.efounder.frame.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.core.xml.StubObject;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.frame.arcmenu.ArcMenu;
import com.efounder.frame.title.EFTitleView;
import com.efounder.frame.title.EFTitleViewInterface;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.xmlparse.EFAppAccountRegistry;
import com.efounder.message.manager.JFMessageListener;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilemanager.R;
import com.efounder.frame.baseui.EFFragment;
import com.efounder.frame.title.EFPagerSlidingTabStripTitleView;
import com.efounder.frame.xmlparse.EFXmlConstants;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.List;

/**
 * Created by hudq on 2016/8/16.
 * --应用号二级 TabFragment
 */

public class EFAppAccountPagerSlidingTabFragment extends EFFragment implements EFAppAccountTabFragmentInterface,EFTitleViewInterface {
    private String TAG = "EFAppAccountPagerSlidingTabFragment";

    private EFPagerSlidingTabStripTitleView efSlidingTabStripTitleView;
    /**此EFPagerSlidingTabFragment 对应的底部TabBar的position **/
    private int position;
    /**viewPager的默认显示位置**/
    private int initPosition = -1;
//    /**onCreateView是否执行完**/
//    private boolean isCreatedView = false;

    private StubObject stubObject;
    private List<StubObject> dataList;
    private ViewPager viewPager;

    private ArcMenu arcMenu;

    private EFAppAccountPagerSlidingTabFragmentHelper helper;

    private AppAccountMessageListener messageListener;

    private Handler handler = new MyHandler(this);

    @Override
    public EFTitleView getEFTitleView() {
        return efSlidingTabStripTitleView;
    }

    private static class MyHandler extends Handler{
        WeakReference<EFAppAccountPagerSlidingTabFragment> weakReference;

        public MyHandler(EFAppAccountPagerSlidingTabFragment fragment) {
            this.weakReference = new WeakReference<EFAppAccountPagerSlidingTabFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            EFAppAccountPagerSlidingTabFragment fragment = weakReference.get();
            if (fragment == null ) return;
            switch (msg.what){
                case 1:
                    //此处不要加减角标数量，直接取未读数量
//                    fragment.helper.indicatorAddNumber(1);
                    fragment.setIndicatorNumber();
                    break;
            }
        }
    }


    public static EFAppAccountPagerSlidingTabFragment newInstance(int position, StubObject stubObject){
        EFAppAccountPagerSlidingTabFragment fragment = new EFAppAccountPagerSlidingTabFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position",position);
        bundle.putSerializable("stubObject", (Serializable) stubObject);
        fragment.setArguments(bundle);
        return  fragment;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        StubObject stubObject = (StubObject) getArguments().getSerializable("stubObject");
        String caption = stubObject.getCaption();
        TAG += "_" + caption + "_" + getArguments().getInt("position");
        Log.i("--",TAG + "------onAttach：");
        //实例化helper
        helper = new EFAppAccountPagerSlidingTabFragmentHelper();
        //注册接口
        if (context instanceof OnViewPagerMeasureCompleteDelegate){
            helper.setOnViewPagerMeasureCompleteDelegate((OnViewPagerMeasureCompleteDelegate) context);
        }
        if (context instanceof EFAppAccountPagerSlidingTabFragmentListener){
            helper.setFragmentListener((EFAppAccountPagerSlidingTabFragmentListener) context);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("--",TAG + "------onCreate:" + savedInstanceState);
        //获取bundle数据,初始化attr
        Bundle bundle = getArguments();
        if (bundle != null){
            position = bundle.getInt("position");
            stubObject = (StubObject) bundle.getSerializable("stubObject");
            dataList = EFAppAccountRegistry.getStubListByElementName(stubObject.getString(EFXmlConstants.ATTR_ID,""));
            if (initPosition == -1){//如果initPosition没有被赋过值（PS：gotoViewPagerFragment方法也会给initPosition赋值）
                String initPositionStr = stubObject.getString(EFXmlConstants.ATTR_INIT_POSITION, "0");
                try {
                    initPosition = Integer.parseInt(initPositionStr);
                } catch (NumberFormatException e) {
                    initPosition = 0;

                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i("--",TAG + "------onCreateView");
        View view = inflater.inflate(R.layout.ef_fragment_with_title,container,false);
        LinearLayout rootLayout = (LinearLayout) view.findViewById(R.id.root_layout);
        //1.创建titleView
        efSlidingTabStripTitleView = helper.createTitleView(getContext(),stubObject);
        rootLayout.addView(efSlidingTabStripTitleView);
        //判断是否显示标题
        Boolean isFullScreen = stubObject.getString(EFXmlConstants
                .ATTR_IS_FULL_SCREEN, "0").equals("1") ? true : false;
        if (isFullScreen)
            efSlidingTabStripTitleView.setVisibility(View.GONE);
        //2.创建ViewPager
        viewPager = helper.createViewPager(getContext(),getChildFragmentManager(),dataList,position);
        rootLayout.addView(viewPager);
        //XXX-自动跳转2 设置viewPager的默认显示项，此方法需要放在setAdapter之后
        viewPager.setCurrentItem(initPosition);
        //3.EfPagerSlidingTabStrip 与 ViewPager关联
        helper.relateViewPager4SlidingTabTitleView(efSlidingTabStripTitleView,viewPager);
//        //onCreateView执行完标记
//        isCreatedView = true;
        //4.初始化ArcMenu
        arcMenu = (ArcMenu) view.findViewById(R.id.arc_menu);
        List<StubObject> menuStubList = EFAppAccountRegistry.getStubListByElementName(stubObject.getString(EFXmlConstants.ATTR_MENU_ID,""));
        StubObject stubByID = EFAppAccountRegistry.getStubByID(stubObject.getString(EFXmlConstants.ATTR_ID, ""));
        String isShowArcMenu = stubByID.getString(EFXmlConstants.ATTR_IS_SHOW_ARCMENU, "");
        helper.initArcMenu(arcMenu,menuStubList,isShowArcMenu);
        //5.注册消息监听
        messageListener = new AppAccountMessageListener();
        JFMessageManager.getInstance().addMessageListener(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID), messageListener);
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.i("--",TAG + "------onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i("--",TAG + "------onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i("--",TAG + "------onResume");
        setIndicatorNumber();
    }

    /**
     * 设置右上角消息数量角标
     */
    private void setIndicatorNumber(){
        int userId = getActivity().getIntent().getIntExtra("id",-1);
        int unreadCount = JFMessageManager.getInstance().getUnReadCount(userId,(byte) 0);
        helper.setIndicatorNumber(unreadCount);
    }

    //TODO 监听消息接受，改变角标

    @Override
    public void onPause() {
        super.onPause();
        Log.i("--",TAG + "------onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("--",TAG + "------onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        Log.i("--",TAG + "------onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            getActivity().unregisterReceiver(helper.getUpdateResReceiver());
        } catch (Exception e) {

        }

        JFMessageManager.getInstance().removeMessageListener(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID),messageListener);
        Log.i("--",TAG + "------onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i("--",TAG + "------onDetach");
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.i("--",TAG + "_" + this.hashCode() + "------setUserVisibleHint--isVisibleToUser:" + isVisibleToUser + "--viewPager中的fragment显示隐藏时调用");

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i("--",TAG + "------onSaveInstanceState--outState:" + outState);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        Log.i("--",TAG + "------onViewStateRestored--savedInstanceState:" + savedInstanceState);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.i("--",TAG + "------onHiddenChanged--hidden:" + hidden +"--hide，show时调用此生命周期");
        //将此生命周期传递给ViewPager中显示的Fragment
        EFAppAccountPagerSlidingTabFragmentPagerAdapter fragmentPagerAdapter = (EFAppAccountPagerSlidingTabFragmentPagerAdapter) viewPager.getAdapter();
        Fragment currentFragment = fragmentPagerAdapter.getCurrentFragment();
        if (currentFragment != null){
            currentFragment.onHiddenChanged(hidden);
        }
        if (!hidden){
            setIndicatorNumber();
        }
    }

    @Override
    public void gotoViewPagerFragment(int viewPagerFragmentPosition) {
        //判断viewPager是否创建（是否执行了onCreateView）
        this.initPosition = viewPagerFragmentPosition;
        if (viewPager != null){
            viewPager.setCurrentItem(viewPagerFragmentPosition);
        }
    }

    @Override
    public ArcMenu getArcMenu() {
        return arcMenu;
    }

    /***
     * ViewPager绘制完成的委派
     * ps:只有ViewPager绘制完成，才会实例化完成其中的Fragment，此接口由{@link EFAppAccountMainActivity}实现，
     * 处理隐藏Fragment的操作
     */
    public interface OnViewPagerMeasureCompleteDelegate{
        public void onViewPagerMeasureComplete(int position);
    }

    public interface EFAppAccountPagerSlidingTabFragmentListener{

        public void onClickLeftViewListener(View view);

    }

    private class AppAccountMessageListener implements JFMessageListener{
        @Override
        public void onReceive(IMStruct002 imStruct002) {
            int userId = getActivity().getIntent().getIntExtra("id",-1);
            if (userId == imStruct002.getFromUserId()){
                handler.sendEmptyMessage(1);
            }
        }

        @Override
        public void onUpdate(int i, IMStruct002 imStruct002) {

        }

        @Override
        public void onFailure(int i, IMStruct002 imStruct002) {

        }
    }

}
